<?php

// PHP雪里开轻量级报修系统 V1.0Beta
// 演示地址: http://baoxiu.chalide.cn
// 更新关注: /weivote
// 文件路径: sys/libx.php
// 文件大小: 11546 字节
// 最后修改时间: 2025-05-21 17:31:15
// 作者: yujianyue
// 邮件: 15058593138@qq.com
// 版权所有,保留发行权和署名权

/**
 * 本文件功能：系统管理员-报修管理
 * 版权声明：保留发行权和署名权
 * 作者信息：功能反馈:15058593138@qq.com(手机号同微信)
 */

// 处理AJAX请求
if (isset($_GET['act'])) {
    switch ($_GET['act']) {
        case 'delete':
            // 删除报修记录
            $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
            
            if ($id <= 0) {
                json_error('无效的报修ID');
            }
            
            // 开始事务
            $db->beginTransaction();
            
            try {
                // 先删除沟通记录
                $db->delete('hist', "bxiu_id = {$id}");
                
                // 再删除报修记录
                $result = $db->delete('bxiu', "id = {$id}");
                
                if (!$result) {
                    throw new Exception('删除报修记录失败: ' . $mysqli->error);
                }
                
                // 提交事务
                $db->commit();
                
                json_success('删除成功');
            } catch (Exception $e) {
                // 回滚事务
                $db->rollback();
                
                json_error($e->getMessage());
            }
            break;
            
        case 'status':
            // 修改状态
            $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
            $status = isset($_POST['status']) ? trim($_POST['status']) : '';
            
            if ($id <= 0) {
                json_error('无效的报修ID');
            }
            
            if (!in_array($status, ['未处理', '处理中', '已完成', '已关闭'])) {
                json_error('无效的状态');
            }
            
            // 更新状态
            $data = [
                'status' => $status,
                'update_time' => date('Y-m-d H:i:s')
            ];
            
            $result = $db->update('bxiu', $data, "id = {$id}");
            
            if ($result) {
                json_success('状态修改成功');
            } else {
                json_error('状态修改失败: ' . $mysqli->error);
            }
            break;
    }
    exit;
}

// 包含头部
include './inc/head.php';

// 获取查询参数
$keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';
$status = isset($_GET['status']) ? trim($_GET['status']) : '';
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$page_size = 10;

// 构建查询条件
$condition = "1=1";

if (!empty($keyword)) {
    $keyword = $mysqli->real_escape_string($keyword);
    $condition .= " AND (title LIKE '%{$keyword}%' OR location LIKE '%{$keyword}%')";
}

if (!empty($status)) {
    $status = $mysqli->real_escape_string($status);
    $condition .= " AND status = '{$status}'";
}

if ($user_id > 0) {
    $condition .= " AND user_id = {$user_id}";
}

// 获取分页数据
$pager = $db->pager('bxiu', $condition, '*', 'create_time DESC', $page, $page_size);
$repairs = $pager['data'];

// 获取用户列表（用于筛选）
$users = $db->getAll('stux', "1=1", 'id, xuehao, realname');
?>
<div class="card">
    <div class="card-header">
        <form class="search-form" method="get" action="">
            <input type="hidden" name="do" value="libx">
            <div class="search-container">
              <h2 class="page-title">报修管理</h2>
                <div class="search-item">
                    <input type="text" class="form-control" name="keyword" placeholder="搜索标题、位置" value="<?php echo htmlspecialchars($keyword); ?>">
                </div>
                <div class="search-item">
                    <select class="form-control" name="user_id">
                        <option value="0">全部用户</option>
                        <?php foreach ($users as $user): ?>
                        <option value="<?php echo $user['id']; ?>" <?php echo $user_id == $user['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($user['realname'] . ' (' . $user['xuehao'] . ')'); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="search-item">
                    <select class="form-control" name="status">
                        <option value="">全部状态</option>
                        <option value="未处理" <?php echo $status == '未处理' ? 'selected' : ''; ?>>未处理</option>
                        <option value="处理中" <?php echo $status == '处理中' ? 'selected' : ''; ?>>处理中</option>
                        <option value="已完成" <?php echo $status == '已完成' ? 'selected' : ''; ?>>已完成</option>
                        <option value="已关闭" <?php echo $status == '已关闭' ? 'selected' : ''; ?>>已关闭</option>
                    </select>
                </div>
                <div class="search-item">
                    <button type="submit" class="btn btn-primary">搜索</button>
                </div>
            </div>
        </form>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>标题</th>
                        <th>位置</th>
                        <th>提交人</th>
                        <th>状态</th>
                        <th>提交时间</th>
                        <th>最后更新</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($repairs)): ?>
                    <tr>
                        <td colspan="8" class="text-center">暂无记录</td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($repairs as $repair): ?>
                    <tr>
                        <td><?php echo $repair['id']; ?></td>
                        <td><?php echo htmlspecialchars($repair['title']); ?></td>
                        <td><?php echo htmlspecialchars($repair['location']); ?></td>
                        <td><?php echo get_user_name($repair['user_id'], $mysqli); ?></td>
                        <td><?php echo status_label($repair['status']); ?></td>
                        <td><?php echo format_date($repair['create_time']); ?></td>
                        <td><?php echo format_date($repair['update_time']); ?></td>
                        <td>
                            <button type="button" class="btn btn-sm btn-primary" onclick="viewRepair(<?php echo $repair['id']; ?>)">详情</button>
                            <button type="button" class="btn btn-sm btn-info" onclick="showStatusForm(<?php echo $repair['id']; ?>, '<?php echo $repair['status']; ?>')">修改状态</button>
                            <button type="button" class="btn btn-sm btn-danger" onclick="deleteRepair(<?php echo $repair['id']; ?>)">删除</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <?php if ($pager['total_pages'] > 1): ?>
        <div class="pagination-container">
            <?php echo pagination($pager['page'], $pager['total_pages'], "?do=libx&keyword=" . urlencode($keyword) . "&status=" . urlencode($status) . "&user_id=" . $user_id); ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- 状态修改模态框 -->
<div id="statusModal" class="modal" style="display: none;">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改状态</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="hideStatusForm()">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="statusForm">
                    <input type="hidden" id="repair_id" name="id" value="0">
                    
                    <div class="form-group">
                        <label for="status">状态</label>
                        <select class="form-control" id="status_select" name="status">
                            <option value="未处理">未处理</option>
                            <option value="处理中">处理中</option>
                            <option value="已完成">已完成</option>
                            <option value="已关闭">已关闭</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="hideStatusForm()">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveStatus()">保存</button>
            </div>
        </div>
    </div>
</div>

<script>
// 查看报修详情
function viewRepair(id) {
    // 创建临时表单提交
    var form = document.createElement('form');
    form.method = 'GET';
    form.action = 'sus.php';
    
    var doInput = document.createElement('input');
    doInput.type = 'hidden';
    doInput.name = 'do';
    doInput.value = 'repa';
    form.appendChild(doInput);
    
    var idInput = document.createElement('input');
    idInput.type = 'hidden';
    idInput.name = 'id';
    idInput.value = id;
    form.appendChild(idInput);
    
    document.body.appendChild(form);
    form.submit();
}

// 显示状态修改表单
function showStatusForm(id, status) {
    document.getElementById('repair_id').value = id;
    document.getElementById('status_select').value = status;
    document.getElementById('statusModal').style.display = 'block';
}

// 隐藏状态修改表单
function hideStatusForm() {
    document.getElementById('statusModal').style.display = 'none';
}

// 保存状态
function saveStatus() {
    var formData = getFormData('statusForm');
    
    ajax('?do=libx&act=status', formData, function(response) {
        if (response.status === 'success') {
            showToast(response.msg, 'success');
            hideStatusForm();
            
            // 刷新页面
            setTimeout(function() {
                window.location.reload();
            }, 1500);
        } else {
            showToast(response.msg, 'error');
        }
    });
}

// 删除报修记录
function deleteRepair(id) {
    if (!confirm('确定要删除这条报修记录吗？此操作不可恢复，且会同时删除所有相关的沟通记录！')) {
        return;
    }
    
    ajax('?do=libx&act=delete', {id: id}, function(response) {
        if (response.status === 'success') {
            showToast(response.msg, 'success');
            
            // 刷新页面
            setTimeout(function() {
                window.location.reload();
            }, 1500);
        } else {
            showToast(response.msg, 'error');
        }
    });
}

// 模态框事件处理
document.addEventListener('click', function(event) {
    var modal = document.getElementById('statusModal');
    if (event.target === modal) {
        hideStatusForm();
    }
});
</script>